﻿using System;
using System.Collections.Generic;
using MangoCannon.Framework.Socket;

namespace MangoCannon.Framework.Base
{
    /// <summary>
    /// 会话管理器
    /// </summary>
    public class ClientSessionManager
    {
        #region 单例
        private static ClientSessionManager csm = null;
        private static Dictionary<string, ClientSession> sessions;//<IP,会话>
        private ClientSessionManager()
        {
            sessions = new Dictionary<string, ClientSession>();
        }

        public static ClientSessionManager getIns()
        {
            if (csm == null)
            {
                csm = new ClientSessionManager();
            }
            return csm;
        }
        #endregion

        public ClientSession newSession(ClientHandle ch)
        {
            ClientSession ses = new ClientSession { sessionOriginalClient = ch, session = new Dictionary<string, object>() };
            if (sessions.ContainsKey(ch.ipAddress.ToString()))
            {
                ses = getSession(ch); //找回原有的会话
            }
            else
            {
                sessions.Add(ch.ipAddress.ToString(), ses);
            }
            return ses;
        }

        public bool delSession(ClientHandle ch)
        {
            ClientSession cs;
            if (sessions.TryGetValue(ch.ipAddress.ToString(),out cs))
            {
                cs.session.Clear();
                cs.sessionOriginalClient = null;
                sessions.Remove(ch.ipAddress.ToString());
                return true;
            }
            else
            {
                return false;
            }
        }

        public ClientSession getSession(ClientHandle ch)
        {
            ClientSession cs;
            if (sessions.TryGetValue(ch.ipAddress.ToString(),out cs))
            {
                return cs;
            }
            else
            {
                return null;
            }
        }

        public void clearAll()
        {
            try
            {
                sessions.Clear();
            }
            catch (Exception)
            {
            }
        }
    }
}
